import React from 'react';
import {
    View,
    StyleSheet,
    TouchableOpacity,
    Image,
    Platform,
    Dimensions
} from 'react-native';

import PropTypes from 'prop-types';
import Label from '../label';

import { getButtonStyle } from './buttonStyle.js';
import Variables from '../../config/theme/styles/index';


export default class Button extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            isActive: false,
            isWideScreen: false // 鸿蒙适配是否宽屏
        }
    }

    componentDidMount() {
        // 适配鸿蒙折叠屏动态更新组件
        this.addEventListenerScreenWidth = Dimensions.addEventListener('change', this.setIsWideScreen)
    }
    componentWillUnmount() {
        // 适配鸿蒙折叠屏动态更新组件
        if (this.addEventListenerScreenWidth) {
            this.addEventListenerScreenWidth = null
        }
    }
    setIsWideScreen = () => {
        const screenWidth = Dimensions.get('window').width;
        if (screenWidth) {
            this.setState({
                isWideScreen: screenWidth > 500 && screenWidth < 800
            })
        }
    }

    _onPress(e) {
        if (Platform.OS == 'web') {
            e.preventDefault();
        };
        if (typeof this.props.onPress == 'function') {
            this.props.onPress(this.props.title);
        }
    }

    _onPressIn() {

        if (!this.props.disabled) {
            this.setState({
                isActive: true
            })
        }
    }

    _onPressOut() {

        if (!this.props.disabled) {
            this.setState({
                isActive: false
            })
        }
    }


    //处理点击事件的时候的换肤样式
    updateActive = (active, ButtonStyle) => {
        let color = ""
        if (!this.props.disabled) {
            switch (this.props.type) {
                case "primary":

                    color = active ? ButtonStyle.buttonPrimaryFillActive : ButtonStyle.buttonPrimaryFill

                    break;
                case "secondary":
                    color = active ? this.props.secondaryPressInColor || ButtonStyle.buttonSecondaryFillActive : ButtonStyle.buttonSecondaryFill
                    break;
                case "link":
                    color = active ? ButtonStyle.buttonLinkFillActive : ButtonStyle.buttonLinkFill
                    break;
                case "textlink":
                    color = active ? ButtonStyle.linkTextFillActive : ButtonStyle.linkTextColor
                    break;
                default:
                    break;
            }
        }

        return color              //返回的是button按钮的背景色
    }



    render() {

        let { title, type, size, hasIcon, source, disabled, isRadius, hasMargin, buttonHeight, buttonWidth, borderRadius, disabledColor, disabledTextColor, pressInColor, isCustomizedFontSize, buttonFontSize } = this.props;
        const sWidth = Dimensions.get('window').width;

        //获取button的样式变量表 和 所需样式
        let { styles, ButtonStyle } = getButtonStyle(Variables)
        const imageStyles = [styles.image];
        const primaryStyles = [styles.primary, { width: sWidth - 15 * 2 }];
        const secondaryStyles = [styles.secondary, { width: sWidth - 15 * 2 }];
        const linkStyles = [styles.link, { width: sWidth - 15 * 2 }];
        const textLinkStyles = [styles.textlink, { width: sWidth - 15 * 2 }];
        let image = null;
        let text = null;
        let typeFontStyle = []
        switch (size) {
            case 'normal':
                if (hasIcon) {
                    image = (<Image style={imageStyles} source={source} />);
                    primaryStyles.push({ paddingHorizontal: 24 });
                    secondaryStyles.push({ paddingHorizontal: 24 });
                    linkStyles.push({ paddingHorizontal: 24 });
                    textLinkStyles.push({ paddingHorizontal: 24 });
                }
                primaryStyles.push({ ...styles.xlargeContainer });
                secondaryStyles.push({ ...styles.xlargeContainer });
                linkStyles.push({ ...styles.xlargeContainer });
                textLinkStyles.push({ ...styles.xlargeContainer });
                typeFontStyle.push({ ...styles.xlargeSize })
                break;
            case 'middle':
                if (hasIcon) {
                    image = (<Image style={imageStyles} source={source} />);
                    primaryStyles.push({ width: (sWidth - 15 * 2) / 2 });
                    secondaryStyles.push({ width: (sWidth - 15 * 2) / 2 });
                    linkStyles.push({ width: (sWidth - 15 * 2) / 2 })
                    textLinkStyles.push({ width: (sWidth - 15 * 2) / 2 })
                }
                primaryStyles.push({ ...styles.xlargeContainer, width: (sWidth - 15 * 2) / 2 });
                secondaryStyles.push({ ...styles.xlargeContainer, width: (sWidth - 15 * 2) / 2 });
                linkStyles.push({ ...styles.xlargeContainer, width: (sWidth - 15 * 2) / 2 });
                textLinkStyles.push({ ...styles.xlargeContainer, width: (sWidth - 15 * 2) / 2 });
                typeFontStyle.push({ ...styles.xlargeSize })
                break;
            case 'small':
                primaryStyles.push({ ...styles.xlargeContainer, width: (sWidth - 15 * 2) / 3 });
                secondaryStyles.push({ ...styles.xlargeContainer, width: (sWidth - 15 * 2) / 3 });
                linkStyles.push({ ...styles.xlargeContainer, width: (sWidth - 15 * 2) / 3 });
                textLinkStyles.push({ ...styles.xlargeContainer, width: (sWidth - 15 * 2) / 3 });
                typeFontStyle.push({ ...styles.xlargeSize })
                break;
            case 'smallest':
                if (isRadius) {
                    primaryStyles.push({ ...styles.medium, width: null, minWidth: 0 });
                    secondaryStyles.push({ ...styles.medium, width: null, minWidth: 0 });
                    linkStyles.push({ ...styles.medium, width: null, minWidth: 0 });
                    textLinkStyles.push({ ...styles.medium, width: null, minWidth: 0 });
                } else {
                    primaryStyles.push({ ...styles.medium, width: null, minWidth: 0, borderRadius: 0 });
                    secondaryStyles.push({ ...styles.medium, width: null, minWidth: 0, borderRadius: 0 });
                    linkStyles.push({ ...styles.medium, width: null, minWidth: 0, borderRadius: 0 });
                    textLinkStyles.push({ ...styles.medium, width: null, minWidth: 0, borderRadius: 0 });
                }
                typeFontStyle.push({ ...styles.smallestSize })
                primaryStyles.push({ paddingHorizontal: ButtonStyle.buttonSmallesPaddingHorizotal });
                secondaryStyles.push({ paddingHorizontal: ButtonStyle.buttonSmallesPaddingHorizotal });
                linkStyles.push({ paddingHorizontal: ButtonStyle.buttonSmallesPaddingHorizotal });
                textLinkStyles.push({ paddingHorizontal: ButtonStyle.buttonSmallesPaddingHorizotal });
                break;
            case 'M':
                if (isRadius) {
                    primaryStyles.push({ ...styles.medium, width: null, minWidth: 80, });
                    secondaryStyles.push({ ...styles.medium, width: null, minWidth: 80 });
                    linkStyles.push({ ...styles.medium, width: null, minWidth: 80 });
                    textLinkStyles.push({ ...styles.medium, width: null, minWidth: 80 });
                } else {
                    primaryStyles.push({ ...styles.medium, width: null, minWidth: 80, borderRadius: 0 });
                    secondaryStyles.push({ ...styles.medium, width: null, minWidth: 80, borderRadius: 0 });
                    linkStyles.push({ ...styles.medium, width: null, minWidth: 80, borderRadius: 0 });
                    textLinkStyles.push({ ...styles.medium, width: null, minWidth: 80, borderRadius: 0 });
                }
                typeFontStyle.push({ ...styles.smallestSize })
                primaryStyles.push({ paddingHorizontal: ButtonStyle.buttonSelfPaddingHorizotal });
                secondaryStyles.push({ paddingHorizontal: ButtonStyle.buttonSelfPaddingHorizotal });
                linkStyles.push({ paddingHorizontal: ButtonStyle.buttonSelfPaddingHorizotal });
                textLinkStyles.push({ paddingHorizontal: ButtonStyle.buttonSelfPaddingHorizotal });
                break;
            case 'L':
                if (isRadius) {
                    primaryStyles.push({ ...styles.large, width: (sWidth - 15 * 2) / 2 });
                    secondaryStyles.push({ ...styles.large, width: (sWidth - 15 * 2) / 2 });
                    linkStyles.push({ ...styles.large, width: (sWidth - 15 * 2) / 2 });
                    textLinkStyles.push({ ...styles.large, width: (sWidth - 15 * 2) / 2 });
                } else {
                    primaryStyles.push({ ...styles.large, borderRadius: 0, width: (sWidth - 15 * 2) / 2 });
                    secondaryStyles.push({ ...styles.large, borderRadius: 0, width: (sWidth - 15 * 2) / 2 });
                    linkStyles.push({ ...styles.large, borderRadius: 0, width: (sWidth - 15 * 2) / 2 });
                    textLinkStyles.push({ ...styles.large, borderRadius: 0, width: (sWidth - 15 * 2) / 2 });
                }
                typeFontStyle.push({ ...styles.largeSize })
                break;
            case 'S':
                if (isRadius) {
                    primaryStyles.push({ ...styles.small, width: null, minWidth: 0 });
                    secondaryStyles.push({ ...styles.small, width: null, minWidth: 0 });
                    linkStyles.push({ ...styles.small, width: null, minWidth: 0 });
                    textLinkStyles.push({ ...styles.small, width: null, minWidth: 0 });
                } else {
                    primaryStyles.push({ ...styles.small, width: null, minWidth: 0, borderRadius: 0 });
                    secondaryStyles.push({ ...styles.small, width: null, minWidth: 0, borderRadius: 0 });
                    linkStyles.push({ ...styles.small, width: null, minWidth: 0, borderRadius: 0 });
                    textLinkStyles.push({ ...styles.small, width: null, minWidth: 0, borderRadius: 0 });
                }
                primaryStyles.push({ paddingHorizontal: ButtonStyle.buttonSSizePaddingHorizotal });
                secondaryStyles.push({ paddingHorizontal: ButtonStyle.buttonSSizePaddingHorizotal });
                linkStyles.push({ paddingHorizontal: ButtonStyle.buttonSSizePaddingHorizotal });
                textLinkStyles.push({ paddingHorizontal: ButtonStyle.buttonSSizePaddingHorizotal });
                typeFontStyle.push({ ...styles.sSize })
                break;
            default:
                break;
        }
        // // 是否圆角   
        if (isRadius && borderRadius) {
            primaryStyles.push({ borderRadius: borderRadius });
            secondaryStyles.push({ borderRadius: borderRadius });
            linkStyles.push({ borderRadius: borderRadius });
            textLinkStyles.push({ borderRadius: borderRadius })
        }

        // 添加margin边距
        if (hasMargin) {
            primaryStyles.push({ marginLeft: 3 });
            secondaryStyles.push({ marginLeft: 3 });
            linkStyles.push({ marginLeft: 3 });
            textLinkStyles.push({ marginLeft: 3 });
        }



        //处理button点击事件的换肤
        let activeColor = this.updateActive(this.state.isActive, ButtonStyle)

        // 处理props属性传过来的背景色
        if (pressInColor && this.state.isActive) {
            if (type != "secondary") {
                activeColor = pressInColor
            }
        } else if (this.props.activeColor && !this.state.isActive) {
            activeColor = this.props.activeColor
        }

        let newTitle;
        if (size == "small" && title.length > 4) {

            newTitle = title.substr(0, 4) + "..."
        } else {
            newTitle = title
        }

        if (buttonHeight) {
            primaryStyles.push({ height: buttonHeight });
            secondaryStyles.push({ height: buttonHeight });
            linkStyles.push({ height: buttonHeight });
            textLinkStyles.push({ height: buttonHeight });
        }
        // 按钮宽度
        if (buttonWidth) {
            primaryStyles.push({ width: buttonWidth });
            secondaryStyles.push({ width: buttonWidth });
            linkStyles.push({ width: buttonWidth });
            textLinkStyles.push({ width: buttonWidth });
        }
        //添加自定义font-size
        if (isCustomizedFontSize) {
            typeFontStyle.push({ fontSize: buttonFontSize })
        }
        //定义type样式
        let typeWrapperStyle = []
        switch (type) {
            case "primary":
                typeWrapperStyle = [primaryStyles, { backgroundColor: disabled ? disabledColor || ButtonStyle.buttonPrimaryFillDisable : activeColor }]

                text = (
                    <Label text={newTitle} textAlign={'center'} labelStyle={[typeFontStyle, { color: disabled ? disabledTextColor || ButtonStyle.buttonPrimaryColorDisable : ButtonStyle.buttonPrimaryColor }]} numberOfLines={2} />
                )
                break;
            case "secondary":
                typeWrapperStyle = [secondaryStyles, { backgroundColor: disabled ? disabledColor || ButtonStyle.buttonSecondaryFillDisable : activeColor, borderWidth: disabled ? ButtonStyle.buttonSecondaryBorderWidthDisable : 1 }]

                text = (
                    <Label text={newTitle} labelStyle={[typeFontStyle, { color: disabled ? disabledTextColor || ButtonStyle.buttonSecondaryColorDisable : ButtonStyle.buttonSecondaryColor }]} textAlign={'center'} numberOfLines={2} />
                )
                break;
            case "link":
                typeWrapperStyle = [linkStyles, { backgroundColor: disabled ? disabledColor || ButtonStyle.buttonSecondaryFillDisable : activeColor, borderWidth: disabled ? ButtonStyle.buttonSecondaryBorderWidthDisable : 1 }]

                text = (
                    <Label text={newTitle} labelStyle={[typeFontStyle, { color: disabled ? disabledTextColor || ButtonStyle.buttonTextLinkColorDisable : ButtonStyle.buttonTextLinkColor }]} textAlign={'center'} numberOfLines={2} />
                )
                break;
            case "textlink":
                typeWrapperStyle = [textLinkStyles]
                text = (
                    <Label text={newTitle} labelStyle={[typeFontStyle, { color: activeColor, fontSize: ButtonStyle.linkTextFont }]} textAlign={'center'} numberOfLines={2} />
                )
                break;
            default:
                break;
        }
        return (
            <TouchableOpacity
                activeOpacity={1}
                disabled={disabled}
                onPressIn={() => this._onPressIn()}
                onPressOut={() => this._onPressOut()}
                onPress={this._onPress.bind(this)}
            >
                <View style={typeWrapperStyle} >
                    {image}
                    {text}
                </View>
            </TouchableOpacity>
        );
    }
}


// 按钮属性类型
Button.propTypes = {
    title: PropTypes.string,
    //按钮文字
    onPress: PropTypes.func,
    //按钮点击事件
    type: PropTypes.oneOf(['primary', 'secondary', 'link', 'textlink']),
    //按钮类型（实心、描边）
    size: PropTypes.oneOf(['smallest', 'small', 'middle', 'normal', 'M', "L", "S"]),
    //按钮尺寸
    isRadius: PropTypes.bool,
    //是否圆角
    disabled: PropTypes.bool,
    //是否禁用
    hasIcon: PropTypes.bool,
    //是否有图片
    source: PropTypes.any,
    //图片路径
    hasMargin: PropTypes.bool,
    //左边距
    buttonHeight: PropTypes.number,
    //按钮高度
    buttonWidth: PropTypes.number,
    //按钮宽度
    activeColor: PropTypes.string,
    //按钮颜色
    pressInColor: PropTypes.string,
    //按钮按下时的颜色
    borderRadius: PropTypes.number,
    //按钮圆角尺寸
    disabledColor: PropTypes.string,
    //按钮禁用的颜色
    disabledTextColor: PropTypes.string,
    //(新增)按钮禁用的文字颜色
    secondaryPressInColor: PropTypes.string,
    //(新增)次要按钮按下时背景颜色
    isCustomizedFontSize: PropTypes.bool,
    // 是否要自定义button字体大小
    buttonFontSize: PropTypes.number
    // 自定义button字体大小
};

Button.defaultProps = {
    title: '',
    type: 'primary',
    size: 'normal',
    isRadius: false,
    disabled: false,
    hasIcon: false,
    hasMargin: false,
    isCustomizedFontSize: false
};
